require 'rubygems'
require_gem 'postgres'

class Database
  attr_reader :conn

  def initialize
    @conn = PGconn.connect('localhost', 5432, '', '', 
      'reality_development', 'postgres', '240374')
  end

  def query(sql)
    Query.new(@conn, sql)
  end  
end

class Query
  attr_reader :result, :fields
  
  def initialize(conn, sql)
    @conn = conn
    @sql = sql
  end
  
  def execute(*args)
    @result = @conn.exec(@sql)
    @fields = @result.fields.map {|s| s.to_sym}
  end
  
  def each(&block)
    row = {}
    @result.each do |r|
      r.each_index {|i| row[@fields[i]] = r[i]}
      block.call(row)
    end
  end
  
  def row_count
    @result.num_tuples
  end
end

db = Database.new
q = db.query("SELECT * FROM nodes WHERE path LIKE '/js%'")
q.execute
q.each {|r| puts r[:path]}
puts q.row_count

##################################

class Node < Record
  after_create {
    
  }
end

Node[123] #=> Node instance
Node[:path => '/sharon'] #=> Node instance
Node.all #=> result set
